﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using WebHttpApi.WebHttpApi.Core;

namespace WebHttpApi.WebHttpApi.HttpApi
{
    /// <summary>
    /// TcLora 的摘要说明：济宁天成 集中器 + LoRa水表 指令类
    /// </summary>
    public class TcLora
    {
        public static string str_DeviceId = "";                //集中器地址逆序排列
        public static string str_MonitorPoint = "";            //表监测点号逆序排列
        public static string str_MeterType = "";               //表类型 16进制

        public static string str_MeterId = "";                 //表地址逆序排列
        public static string str_Comm = "";                    //命令串
        public static string str_CommPam = "";                 //参数串

        public static string str_zxjg = "0";                   //执行结果  -  0：未执行 | 1：已执行
        public static string str_xyjx = "";                    //协议解析  -  什么命令（日志）
        public static string str_rzlx = "发送";                //日志类型  -  存储：命令写数据库（日志）
        public static string str_xymc = "";                    //协议名称  -  命令类型名称： 控阀、休眠等（日志）
        public static string str_oper = "WebHttpApi";          //操作员    -  指令、日志

        public static string str_Result = "";

        public static string comm_result = "";
        public static string str_jsonParam = "";
        public static DateTime str_dt;

        public static string Lora_Comm(string DeviceId, string MeterType, string MeterId, string Type, string CommPam)
        {
            str_xyjx = "";
            str_xymc = "";

            if (DeviceId != ""&& MeterId != "" && Type != "")
            {
                try
                {
                    str_DeviceId = DeviceId;
                    str_MeterId = MeterId;
                    str_dt = DateTime.Now;

                    string url = System.Configuration.ConfigurationManager.AppSettings["TC_JZQ_URL"].ToString();

                    switch (Type)
                    {
                        //控阀指令 ： 目前只支持单只控阀
                        //Type：43 | 67
                        //CommPam：55、99 | 1、2
                        case "67":
                            {
                                if (CommPam == "85")
                                {
                                    str_CommPam = "1";
                                    str_xyjx = "开阀";
                                }
                                else if (CommPam == "153")
                                {
                                    str_CommPam = "2";
                                    str_xyjx = "关阀";
                                }
                                else
                                {
                                    str_Result = "参数错误";
                                    break;
                                }
                                str_xymc = "控阀";

                                if (MeterType == "81" ||
                                    MeterType == "82" ||
                                    MeterType == "83")
                                {
                                    str_jsonParam = "{\"msg\":\"OP_VALVE_REQ\",\"con\":\"" + str_DeviceId + "\",\"inf\":{\"equId\":{\"equId\":\"" + str_MeterId + "\",\"equType\":32,\"manuId\":\"0000\"},\"op\":{\"opType\":" + str_CommPam + "}}}";

                                    var request = (HttpWebRequest)WebRequest.Create(url);
                                    request.Method = "POST";
                                    request.ContentType = "application/json;charset=UTF-8";
                                    byte[] byteData = Encoding.UTF8.GetBytes(str_jsonParam);

                                    int length = byteData.Length;
                                    request.ContentLength = length;
                                    Stream writer = request.GetRequestStream();
                                    writer.Write(byteData, 0, length);
                                    writer.Close();

                                    var response = (HttpWebResponse)request.GetResponse();
                                    var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();

                                    comm_result = responseString.ToString();

                                    //写接口调用日志
                                    str_Result = Lora_sql(DeviceId, MeterType, MeterId, Type);

                                    JObject json_post = (JObject)JsonConvert.DeserializeObject(comm_result);
                                    string str_comm_result = json_post["inf"]["cause"].ToString();
                                    if (str_comm_result == "17")
                                    {
                                        //控阀成功 ： 返回日志
                                        bool operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_rz(ybdz,xynr,xyjx,xtsj,rzlx,xymc,czy) values ('" +
                                                                                            MeterId + "','" +
                                                                                            comm_result + "','成功','" +
                                                                                            str_dt + "','接收','" +
                                                                                            str_xymc + "','" +
                                                                                            str_oper + "')");
                                    }
                                    else
                                    {
                                        //控阀失败 ： 返回日志
                                        bool operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_rz(ybdz,xynr,xyjx,xtsj,rzlx,xymc,czy) values ('" +
                                                                                            MeterId + "','" +
                                                                                            comm_result + "','失败','" +
                                                                                            str_dt + "','接收','" +
                                                                                            str_xymc + "','" +
                                                                                            str_oper + "')");
                                    }
                                }
                                else
                                {
                                    str_Result = "不支持";
                                }

                                break;
                            }

                        //实时抄表 
                        //Type：53 | 83
                        case "83":
                            {
                                str_xymc = "实时抄表";
                                str_xyjx = "实时抄表";

                                if (MeterType == "81" ||
                                    MeterType == "82" ||
                                    MeterType == "83")
                                {
                                    str_jsonParam = "{\"msg\":\"GET_RDATA_REQ\",\"con\":\"" + str_DeviceId + "\",\"inf\":{\"equId\":{\"equId\":\"" + str_MeterId + "\",\"equType\":32,\"manuId\":\"0000\"}}}";

                                    var request = (HttpWebRequest)WebRequest.Create(url);
                                    request.Method = "POST";
                                    request.ContentType = "application/json;charset=UTF-8";
                                    byte[] byteData = Encoding.UTF8.GetBytes(str_jsonParam);

                                    int length = byteData.Length;
                                    request.ContentLength = length;
                                    Stream writer = request.GetRequestStream();
                                    writer.Write(byteData, 0, length);
                                    writer.Close();

                                    var response = (HttpWebResponse)request.GetResponse();
                                    var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();

                                    comm_result = responseString.ToString();

                                    //写接口调用日志
                                    str_Result = Lora_sql(DeviceId, MeterType, MeterId, Type);

                                    JObject json_post = (JObject)JsonConvert.DeserializeObject(comm_result);
                                    string str_comm_result = json_post["inf"]["cause"].ToString();
                                    if (str_comm_result == "17")
                                    {
                                        //抄表成功 ： 返回日志
                                        bool operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_rz(ybdz,xynr,xyjx,xtsj,rzlx,xymc,czy) values ('" +
                                                                                            MeterId + "','" +
                                                                                            comm_result + "','成功','" +
                                                                                            str_dt + "','接收','" +
                                                                                            str_xymc + "','" +
                                                                                            str_oper + "')");
                                        //获取抄表数据 ： 更新监控表
                                        string back_ybdz = json_post["inf"]["meterData"]["equId"].ToString();
                                        string back_ybdy = json_post["inf"]["meterData"]["voltage"].ToString();
                                        string back_zxlj = json_post["inf"]["meterData"]["cumulatedFlow"].ToString();
                                        string back_fmzt = json_post["inf"]["meterData"]["valveState"].ToString();
                                        if (back_fmzt == "100")
                                        {
                                            back_fmzt = "阀开";
                                        }
                                        else
                                        {
                                            back_fmzt = "阀关";
                                        }
                                        bool operatorlog_jk = WebSdkCore.insert_update_delete("update rp_meter_jk set ybdy='" +
                                                                                               back_ybdy + "',zxlj='" +
                                                                                               back_zxlj + "',fmzt='" +
                                                                                               back_fmzt + "',txsj='" +
                                                                                               str_dt + "',ybsj='" +
                                                                                               str_dt + "' where ybdz='" +
                                                                                               back_ybdz + "'");
                                    }
                                    else
                                    {
                                        //抄表失败 ： 返回日志
                                        bool operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_rz(ybdz,xynr,xyjx,xtsj,rzlx,xymc,czy) values ('" +
                                                                                            MeterId + "','" +
                                                                                            comm_result + "','失败','" +
                                                                                            str_dt + "','接收','" +
                                                                                            str_xymc + "','" +
                                                                                            str_oper + "')");
                                    }
                                }
                                else
                                {
                                    str_Result = "不支持";
                                }

                                break;
                            }
                    }
                }
                catch
                {
                    str_Result = "设备或仪表编号不正确";
                }
            }
            return str_Result;
        }

        public static string Lora_sql(string DeviceId, string MeterType, string MeterId, string Type)
        {
            //HTTP接口调用日志
            bool operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_rz(ybdz,xynr,xyjx,xtsj,rzlx,xymc,czy) values ('" +
                                                                MeterId + "','" +
                                                                str_jsonParam + "','" +
                                                                str_xyjx + "','" +
                                                                str_dt + "','" +
                                                                str_rzlx + "','" +
                                                                str_xymc + "','" +
                                                                str_oper + "')");
            if (operatorlog == true)
            {
                str_Result = "成功";
            }
            else
            {
                str_Result = "写日志失败";
            }

            return str_Result;
        }
    }
}